//
//  YMWebSocket.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/11/13.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "YMWebSocket.h"
#import <SRWebSocket.h>

static id _instance = nil;
@interface YMWebSocket()<SRWebSocketDelegate>
@property(nonatomic, strong) SRWebSocket *socket;
@property(nonatomic, strong) SYDAccount *account;
@end

@implementation YMWebSocket

+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[YMWebSocket alloc] init];
    });
    return _instance;
}

- (SYDAccount *)account{
    if (!_account) {
        _account = [SYDAccountTool getAccount];
    }
    return _account;
}

- (SRWebSocket *)socket{
    if (!_socket) {
        NSString * urlString = [NSString stringWithFormat:@"ws://202.104.136.228:8071/websocket?userId=%@",self.account.userId];
//        NSString * urlString = @"ws://121.40.165.18:8088";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        _socket = [[SRWebSocket alloc] initWithURLRequest:request];
    }
    return _socket;
}

- (void)send:(id)msg{
    [self.socket send:msg];
}

#pragma mark - SRWebSocketDelegate
- (void)connect{
    self.socket.delegate = self;
    [self.socket open];
}

- (void)exit{
    self.socket.delegate = nil;
    [self.socket close];
    self.socket = nil;
}

- (void)close{
    self.socket.delegate = nil;
    [self.socket close];
    if (_connectBlock) {
        _connectBlock(YMWebSocketStatusColosedByUser, nil);
    }
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    NSLog(@"connect");
    if (_connectBlock) {
        _connectBlock(YMWebSocketStatusConnected, nil);
    }
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    NSLog(@"error:%@", [error localizedDescription]);
    if (_connectBlock) {
        _connectBlock(YMWebSocketStatusFailed, nil);
    }
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    NSLog(@"didCloseWithCode:%ld",(long)code);
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    NSLog(@"msg:%@", message);
    if (_connectBlock) {
        _connectBlock(YMWebSocketStatusReceived, message);
    }
}


@end

